package net.xdclass.user.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.common.enums.BizCodeEnum;
import net.xdclass.common.enums.MailType;
import net.xdclass.user.service.NotifyService;
import net.xdclass.common.utils.CommonUtil;
import net.xdclass.common.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "通知模块")
@RestController
@RequestMapping("/api/user/v1")
public class NotifyController {

    @Autowired
    private Producer captchaProducer;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private NotifyService notifyService;

    /**
     *临时使用10分钟有效，方便测试
     */
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;

    @ApiOperation("发送邮箱注册验证码")
    @GetMapping("/code")
    public JsonData sendRegisterCode(HttpServletRequest request,
                                     @RequestParam("to") String to,
                                     @RequestParam("captcha") String captcha){
        String key = getCaptchaKey(request);
        String cacheKey = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(captcha) && captcha.equalsIgnoreCase(cacheKey)){
            redisTemplate.delete(key);
            return notifyService.sendCaptcha(to, MailType.USER_REGISTERY);
        }
        return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA);
    }

    @ApiOperation("获取图形验证码")
    @GetMapping("/captcha")
    public void getCapta(HttpServletRequest request, HttpServletResponse response){
        String captchaText = captchaProducer.createText();
        String cacheKey = getCaptchaKey(request);
        log.info("生成的验证码是 -> {}", captchaText);
        // 缓存验证码
        redisTemplate.opsForValue().set(cacheKey,captchaText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        BufferedImage image = captchaProducer.createImage(captchaText);
        ServletOutputStream out = null;
        try {
            // 不缓存
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "create_date-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
        } catch (IOException e) {
            log.warn("输出验证码失败 -> {}", e.getMessage());
        }finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                log.warn("输出验证码关闭输出流失败 -> {}", e.getMessage());
            }
        }
    }

    /**
     * 生成缓存的key
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request) {
//        user-service:captcha:xxxx
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "user-service:captcha:" + CommonUtil.MD5(ip + userAgent);
        log.info("ip -> {}, userAgent -> {}, key -> {}", ip, userAgent, key);
        return key;
    }
}
